// 图形子系统示例应用程序 - 演示如何使用GraphicsSubsystem服务
// 仅使用safe Rust

#![forbid(unsafe_code)]

use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::Duration;
use log::{info, error};

// 导入所需服务
use super::{ServiceManager, GraphicsSubsystem};
use super::graphics_subsystem::GraphicsSubsystemError;

// 示例应用程序
pub struct ExampleGraphicsApp {
    service_manager: Arc<Mutex<ServiceManager>>,
    graphics_subsystem: Arc<Mutex<GraphicsSubsystem>>,
    window_id: Option<u64>,
    running: bool,
    app_thread: Option<thread::JoinHandle<()>>,
}

impl ExampleGraphicsApp {
    // 创建新的示例应用程序
    pub fn new(service_manager: Arc<Mutex<ServiceManager>>) -> Result<Self, String> {
        // 获取图形子系统服务
        let graphics_subsystem = service_manager.lock()
            .map_err(|e| format!("Failed to lock service manager: {}", e))?
            .get_graphics_subsystem();
        
        Ok(ExampleGraphicsApp {
            service_manager,
            graphics_subsystem,
            window_id: None,
            running: false,
            app_thread: None,
        })
    }
    
    // 启动示例应用程序
    pub fn run(&mut self) -> Result<(), String> {
        if self.running {
            return Err("Application is already running".to_string());
        }
        
        self.running = true;
        
        // 创建窗口
        self.create_main_window()?;
        
        // 启动应用程序主线程
        let running = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let running_clone = Arc::clone(&running);
        let graphics_subsystem = Arc::clone(&self.graphics_subsystem);
        let window_id = self.window_id.unwrap();
        
        self.app_thread = Some(thread::spawn(move || {
            info!("Example graphics application started");
            
            // 应用程序主循环
            let mut frame_count = 0;
            let start_time = std::time::Instant::now();
            
            while running_clone.load(std::sync::atomic::Ordering::Relaxed) {
                // 每帧更新
                frame_count += 1;
                
                // 每500毫秒更新一次窗口标题，显示FPS
                if frame_count % 30 == 0 {
                    let elapsed = start_time.elapsed();
                    let fps = frame_count as f64 / elapsed.as_secs_f64();
                    
                    let title = format!("ZENrs Graphics Subsystem Demo - FPS: {:.1}", fps);
                    
                    // 在实际实现中，这里应该有更新窗口标题的API
                    info!("{}", title);
                }
                
                // 短暂休眠，避免CPU占用过高
                thread::sleep(Duration::from_millis(16)); // 约60fps
            }
            
            info!("Example graphics application stopped");
        }));
        
        info!("Example graphics application initialized successfully");
        Ok(())
    }
    
    // 创建主窗口
    fn create_main_window(&mut self) -> Result<(), String> {
        if self.window_id.is_some() {
            return Err("Main window already exists".to_string());
        }
        
        // 创建窗口
        let window_id = self.graphics_subsystem.lock()
            .map_err(|e| format!("Failed to lock graphics subsystem: {}", e))?
            .create_window(
                "ZENrs Graphics Subsystem Demo",
                100, 100, // 位置
                800, 600  // 尺寸
            )
            .map_err(|e| format!("Failed to create window: {:?}", e))?;
        
        self.window_id = Some(window_id);
        
        info!("Created main window with ID: {}", window_id);
        
        // 设置窗口为焦点
        self.graphics_subsystem.lock()
            .map_err(|e| format!("Failed to lock graphics subsystem: {}", e))?
            .set_window_focus(window_id, true)
            .map_err(|e| format!("Failed to set window focus: {:?}", e))?;
        
        Ok(())
    }
    
    // 停止示例应用程序
    pub fn stop(&mut self) -> Result<(), String> {
        if !self.running {
            return Ok(());
        }
        
        self.running = false;
        
        // 等待应用程序主线程结束
        if let Some(thread) = self.app_thread.take() {
            if let Err(err) = thread.join() {
                error!("Example graphics application thread panicked: {:?}", err);
            }
        }
        
        // 销毁窗口
        if let Some(window_id) = self.window_id {
            self.graphics_subsystem.lock()
                .map_err(|e| format!("Failed to lock graphics subsystem: {}", e))?
                .destroy_window(window_id)
                .map_err(|e| format!("Failed to destroy window: {:?}", e))?;
            
            self.window_id = None;
        }
        
        info!("Example graphics application stopped successfully");
        Ok(())
    }
    
    // 检查应用程序是否正在运行
    pub fn is_running(&self) -> bool {
        self.running
    }
}

// 实现Drop trait，确保资源被正确清理
impl Drop for ExampleGraphicsApp {
    fn drop(&mut self) {
        let _ = self.stop();
    }
}

// 运行示例应用程序的辅助函数
pub fn run_example_graphics_app() -> Result<(), String> {
    info!("Initializing example graphics application");
    
    // 创建服务管理器
    let service_manager = Arc::new(Mutex::new(
        ServiceManager::new().map_err(|e| format!("Failed to create service manager: {}", e))?
    ));
    
    // 启动所有服务
    service_manager.lock()
        .map_err(|e| format!("Failed to lock service manager: {}", e))?
        .start_all_services()
        .map_err(|e| format!("Failed to start all services: {}", e))?;
    
    // 创建并运行示例应用程序
    let mut app = ExampleGraphicsApp::new(Arc::clone(&service_manager))
        .map_err(|e| format!("Failed to create example graphics application: {}", e))?;
    
    app.run()
        .map_err(|e| format!("Failed to run example graphics application: {}", e))?;
    
    info!("Example graphics application is running. Press Ctrl+C to exit.");
    
    // 运行一段时间后自动停止（实际应用程序可能会等待用户输入）
    thread::sleep(Duration::from_secs(10));
    
    // 停止示例应用程序
    app.stop()
        .map_err(|e| format!("Failed to stop example graphics application: {}", e))?;
    
    info!("Example graphics application demo completed");
    
    Ok(())
}